require 'spotify/charts/version'
require 'spotify/charts/client'
require 'spotify/charts/track'
require 'spotify/charts/track_parser'

module Spotify
  module Charts
    class << self
      def available_metrics
        client.request('/')
      end

      def available_countries
        client.request('/most_viral/')
      end

      def available_time_window_types(country)
        client.request("/most_viral/#{country}/")
      end

      def available_dates(country, time_window_type)
        client.request("/most_viral/#{country}/#{time_window_type}/")
      end

      def most_viral(country, time_window_type, date)
        extract_tracks("/most_viral/#{country}/#{time_window_type}/#{date}")
      end

      def most_streamed(country, time_window_type, date)
        extract_tracks("/most_streamed/#{country}/#{time_window_type}/#{date}")
      end

      private

      def client
        @client ||= Spotify::Charts::Client.new
      end

      def extract_tracks(endpoint)
        json = client.request(endpoint)['tracks']

        json.inject([]) do |tracks, item|
          tracks << TrackParser.new(item).track
        end
      end
    end
  end
end
